import ClassPathBeanDefinitionScanner from "@framework/context/ClassPathBeanDefinitionScanner";
import DefaultListableBeanFactory from "@framework/bean/DefaultListableBeanFactory";
import ConstructBeanProvider from "@framework/support/ConstructBeanProvider";
import AutowiredBeanProvider from "@framework/support/AutowiredBeanProvider";
import KoaBootRouterProvider from "@framework/support/KoaBootRouterProvider";
import KoaBootServerProvider from "@framework/support/KoaBootServerProvider";
import KoaBootFile from "@framework/web/KoaBootFile";
import Path from "node:path";
import KoaBootUtil from "@framework/util/KoaBootUtil";

/**
 * 装饰器扫描上下文
 */
class DecoratorApplicationContext {

    /**
     * Bean构造工厂
     * @private
     */
    private readonly beanFactory: DefaultListableBeanFactory;

    /**
     * 资源扫描器
     * @private
     */
    private readonly definitionScanner: ClassPathBeanDefinitionScanner;

    /**
     * 初始化启动器
     * @private
     */
    private  constructBeanProvider: ConstructBeanProvider;

    /**
     * 实例化Bean。并且自动注入属性
     * @private
     */
    private autowiredBeanProvider: AutowiredBeanProvider;

    /**
     * KoaBoot路由处理器
     * @private
     */
    private koaBootRouterProvider: KoaBootRouterProvider;

    /**
     * KoaBoot服务处理器
     * @private
     */
    private koaBootServerProvider: KoaBootServerProvider;

    /**
     * 构造函数
     */
    constructor() {
        this.definitionScanner = new ClassPathBeanDefinitionScanner();
        this.beanFactory = new DefaultListableBeanFactory();
        this.koaBootStartUp();
    }

    /**
     * 启动Koa-Boot项目
     * @private
     */
    private koaBootStartUp() {
        KoaBootUtil.setContext(this);
        const koaBootFile = new KoaBootFile(Path.join(KoaBootFile.getResourcePath(), "banner.txt"));
        console.log(koaBootFile.readString());
        console.log("KoaBoot V1.1");
        this.constructBeanProvider = new ConstructBeanProvider(this.definitionScanner, this.beanFactory);
        this.autowiredBeanProvider = new AutowiredBeanProvider(this.beanFactory);
        this.koaBootRouterProvider = new KoaBootRouterProvider(this.beanFactory);
        this.koaBootServerProvider = new KoaBootServerProvider(this.beanFactory);
    }

    /**
     * 获取Bean实例
     * @param beanName
     */
    public getBean(beanName: string): Object | undefined {
        return this.beanFactory.getBean(beanName);
    }
}

export default DecoratorApplicationContext;